import java.util.StringTokenizer;

class P10489 {

	public static void main(String[] args) {
		int cases = Integer.parseInt(readLn());
		for (int k = 0; k < cases; k++) {
			StringTokenizer st = new StringTokenizer(readLn());
			long friends = Integer.parseInt(st.nextToken());
			long subcases = Integer.parseInt(st.nextToken());
			long total = 0;
			for (int j = 0; j < subcases; j++) {
				st = new StringTokenizer(readLn());
				int boxes = Integer.parseInt(st.nextToken());
				long chocolates = 1;
				for (int l = 0; l < boxes; l++) {
					chocolates *= Integer.parseInt(st.nextToken());
					chocolates = chocolates % friends;
				}
				total += chocolates;
				total = total % friends;
			}
			System.out.println(total);
		}
	}

	static String readLn() {
		String newLine = System.getProperty("line.separator");
		StringBuffer buffer = new StringBuffer();
		int car = -1;
		try {
			car = System.in.read();
			while ((car > 0) && (car != newLine.charAt(0))) {
				buffer.append((char) car);
				car = System.in.read();
			}
			if (car == newLine.charAt(0))
				System.in.skip(newLine.length() - 1);
		} catch (java.io.IOException e) {
			return (null);
		}
		if ((car < 0) && (buffer.length() == 0))
			return (null);
		return (buffer.toString()).trim();
	}

}
